<template>
  <div class="login-container">
    <el-form
      ref="loginFormRef"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      autocomplete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">Easy Mall 后台管理系统</h3>
      </div>

      <!-- 用户名 -->
      <el-form-item prop="username">
        <el-input
          ref="usernameRef"
          v-model="loginForm.username"
          placeholder="用户名"
          name="username"
          type="text"
          tabindex="1"
          autocomplete="on"
          prefix-icon="User"
        />
      </el-form-item>

      <!-- 密码 -->
      <el-form-item prop="password">
        <el-input
          ref="passwordRef"
          v-model="loginForm.password"
          :type="passwordVisible ? 'text' : 'password'"
          placeholder="密码"
          name="password"
          tabindex="2"
          autocomplete="on"
          prefix-icon="Lock"
          @keyup.enter="handleLogin"
        >
          <template #suffix>
            <el-icon class="cursor-pointer" @click="passwordVisible = !passwordVisible">
              <View v-if="passwordVisible" />
              <Hide v-else />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      <!-- 验证码 -->
      <el-form-item prop="captcha">
        <div class="captcha-container">
          <el-input
            v-model="loginForm.captcha"
            placeholder="验证码"
            name="captcha"
            tabindex="3"
            autocomplete="off"
            prefix-icon="Key"
            @keyup.enter="handleLogin"
          />
          <div class="captcha-image" @click="refreshCaptcha">
            <img v-if="captchaImg" :src="captchaImg" alt="验证码" />
            <div v-else class="captcha-loading">加载中...</div>
          </div>
        </div>
      </el-form-item>

      <!-- 记住密码 -->
      <div class="remember-container">
        <el-checkbox v-model="loginForm.remember">记住密码</el-checkbox>
      </div>

      <!-- 登录按钮 -->
      <el-button
        :loading="loading"
        type="primary"
        class="login-button"
        @click="handleLogin"
      >
        登录
      </el-button>

      <!-- 角色选择 (仅用于演示) -->
      <div class="role-selector">
        <p class="role-title">演示账号快速登录：</p>
        <div class="role-list">
          <el-button type="info" plain size="small" @click="setRole('admin')">平台管理员</el-button>
          <el-button type="info" plain size="small" @click="setRole('merchant')">商家</el-button>
          <el-button type="info" plain size="small" @click="setRole('service')">商家客服</el-button>
          <el-button type="info" plain size="small" @click="setRole('delivery')">配送员</el-button>
        </div>
      </div>
      
      <!-- 注册链接 -->
      <div class="register-link">
        <router-link to="/register">没有账号？立即注册</router-link>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../../store/user'

// 路由
const router = useRouter()

// 用户store
const userStore = useUserStore()

// 表单引用
const loginFormRef = ref()
const usernameRef = ref()
const passwordRef = ref()

// 密码可见性
const passwordVisible = ref(false)

// 加载状态
const loading = ref(false)

// 验证码图片
const captchaImg = ref('')
const captchaKey = ref('')

// 登录表单
const loginForm = reactive({
  username: 'admin',
  password: '123456',
  captcha: '',
  remember: false
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 6, message: '验证码长度不正确', trigger: 'blur' }
  ]
}

// 刷新验证码
const refreshCaptcha = async () => {
  try {
    const res = await userStore.getCaptcha()
    captchaImg.value = res.captchaImage
    captchaKey.value = res.captchaKey
  } catch (error) {
    console.error('获取验证码失败:', error)
    ElMessage.error('获取验证码失败，请刷新页面重试')
  }
}

// 设置角色（演示用）
const setRole = (role: string) => {
  switch (role) {
    case 'admin':
      loginForm.username = 'admin'
      loginForm.password = '123456'
      break
    case 'merchant':
      loginForm.username = 'merchant'
      loginForm.password = '123456'
      break
    case 'service':
      loginForm.username = 'service'
      loginForm.password = '123456'
      break
    case 'delivery':
      loginForm.username = 'delivery'
      loginForm.password = '123456'
      break
  }
}

// 处理登录
const handleLogin = () => {
  loginFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        await userStore.login(
          loginForm.username,
          loginForm.password,
          loginForm.captcha,
          captchaKey.value
        )
        
        ElMessage.success('登录成功')
        router.push({ path: '/' })
      } catch (error: any) {
        ElMessage.error(error.message || '登录失败，请重试')
        // 刷新验证码
        refreshCaptcha()
      } finally {
        loading.value = false
      }
    } else {
      return false
    }
  })
}

// 组件挂载时获取验证码
onMounted(() => {
  refreshCaptcha()
}
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  width: 100%;
  background-color: #2d3a4b;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  
  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
    
    .remember-container {
      margin-bottom: 20px;
      color: #fff;
    }
    
    .login-button {
      width: 100%;
      margin-bottom: 30px;
    }
    
    .role-selector {
      margin-top: 20px;
      text-align: center;
      
      .role-title {
        color: #fff;
        margin-bottom: 10px;
      }
      
      .role-list {
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;
        
        .el-button {
          margin: 5px;
        }
      }
    }
  }
  
  .title-container {
    position: relative;
    
    .title {
      font-size: 26px;
      color: #eee;
      margin: 0 auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }
  
  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
  
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;
    
    input {
      background: transparent;
      border: 0;
      -webkit-appearance: none;
      border-radius: 0;
      padding: 12px 5px 12px 15px;
      color: #eee;
      height: 47px;
      caret-color: #fff;
      
      &:-webkit-autofill {
        box-shadow: 0 0 0 1000px #283443 inset !important;
        -webkit-text-fill-color: #fff !important;
      }
    }
  }
}
</style>